import { createRouters } from './permission'
import type { ApplicationMenuInfo, UserInfo } from '@/types'
import { UserInfoEnum } from '@/enum'
import { store } from '@/config'

const useUserStore = defineStore(
  'userStore',
  () => {
    const { setAnimateState } = useLayoutStore()
    const [permissionRoutes, setPermissionRoutes] = useState<
      ApplicationMenuInfo[]
    >([])

    const [userInfo, setUserInfo] = useState<Partial<UserInfo>>({} as UserInfo)
    const [isSingleApplication, setIsSingleApplication] = useState(false)
    const [rootPath, setRootPath] = useState('')

    /**
     * 存储动态路由的销毁函数集
     */
    const removeRouteFuns = ref<(() => void)[]>([])
    /** 超级管理员与否 */
    const isAdmin = computed(() => userInfo.value.accountType === '1')

    /** 销毁动态路由 */
    const clearTrendsRoute = () => {
      removeRouteFuns.value.forEach((func: () => void) => func?.())
      // !重置
      removeRouteFuns.value.length = 0
    }
    /**
     * 添加动态路由的销毁函数
     */
    const addRemoveRouteFuns = (func: () => void) => {
      removeRouteFuns.value.push(func)
    }
    const fetchPermissionRoutes = () => {
      const r = createRouters(permissionRoutes.value)
      return r
    }

    const logout = () => {
      setAnimateState(true, {
        fullscreen: true,
        showTitle: true,
        title: '正在退出...',
      })

      localStorage.removeItem(UserInfoEnum.TOKEN)
      setUserInfo({})
      permissionRoutes.value.length = 0
      setIsSingleApplication(false)

      window.location.reload()
      clearTrendsRoute()
    }

    return {
      permissionRoutes,
      isSingleApplication,
      isAdmin,
      fetchPermissionRoutes,
      clearTrendsRoute,
      addRemoveRouteFuns,
      logout,
      setIsSingleApplication,
      userInfo,
      setUserInfo,
      setPermissionRoutes,
      rootPath,
      setRootPath,
    }
  },
  {
    persist: {
      storage: localStorage,
      paths: [
        'permissionRoutes',
        'userInfo',
        'isSingleApplication',
        'rootPath',
      ],
    },
  },
)

/** 非setup中 */
export function useUserStoreHook() {
  return useUserStore(store)
}

export default useUserStore
